package com.campus.campusdelivery.controller;

import com.campus.campusdelivery.dto.ApiResponse;
import com.campus.campusdelivery.dto.LoginRequest;
import com.campus.campusdelivery.dto.LoginResponse;
import com.campus.campusdelivery.dto.RegisterRequest;
import com.campus.campusdelivery.service.AuthService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AuthController {
    
    private final AuthService authService;
    
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            System.out.println("开始登录请求: username=" + request.getUsername());
            LoginResponse response = authService.login(request);
            System.out.println("登录成功: " + request.getUsername());
            return ApiResponse.success("登录成功", response);
        } catch (RuntimeException e) {
            System.err.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            System.err.println("登录时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            return ApiResponse.error("系统错误: " + e.getMessage());
        }
    }
    
    @PostMapping("/register")
    public ApiResponse<Void> register(@Valid @RequestBody RegisterRequest request) {
        try {
            authService.register(request);
            return ApiResponse.success("注册成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PostMapping("/logout")
    public ApiResponse<Void> logout(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            authService.logout(token);
            return ApiResponse.success("退出成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
